package com.ruibang.glass.frequencycontrol.interceptor;

import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSON;
import com.ruibang.glass.common.constants.Constants;
import com.ruibang.glass.common.domain.GlobalUser;
import com.ruibang.glass.frequencycontrol.domain.dto.RequestInfo;
import com.ruibang.glass.frequencycontrol.util.RequestHolder;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;


/**
 * @author 宋锦康
 * 信息收集的拦截器
 */
@Order(1)
@Slf4j
@Component
public class CollectorInterceptor implements HandlerInterceptor {

//    @Autowired
//    private RedisSingleService redisService;

    @Autowired
    private RedisSingleService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        RequestInfo info = new RequestInfo();
        info.setUserId(getUserId(request));
        log.error("获取客户端IP：{}", ServletUtil.getClientIP(request));
        info.setIp(ServletUtil.getClientIP(request));
        RequestHolder.set(info);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestHolder.remove();
    }

    /**
     * 获取userId
     *
     * @return
     */
    public String getUserId(HttpServletRequest request) {
        Object token = request.getHeader(Constants.AUTHORIZATION_HEADER);
        if (token == null) {
            token = request.getAttribute(Constants.AUTHORIZATION_HEADER);
        }
        if (Optional.ofNullable(token).isPresent()) {
            if (redisService.hasKey(token.toString())) {
                String json = redisService.get(token.toString()).toString();
                if (StringUtils.isNotBlank(json)) {
                    return JSON.parseObject(json, GlobalUser.class).getUserId();
                }
            }
        }
        return null;
    }

}